<template>
	<view class="edit-info">
		<view class="flex-box center align-center p-3">
			<button class="avatar-wrapper" :plain="true" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image class="avatar" :src="user.avatar" mode="aspectFill"></image>
				<view class="font2">请选择用户头像</view>
			</button>
		</view>
		<view class="nickname">
			<input class="input" @blur="nicknameBlur" name="nickname" type="nickname" placeholder="请输入昵称" maxlength="10"
				:value="user.nickname" />

		</view>

		<button class="submit-btn" form-type="submit" type="primary" @click="submitBtnClick">
			修改
		</button>

	</view>
</template>
<script>
    import { callWithErrorHandling, reactive } from "vue";
    import { onLoad, onShow } from "@dcloudio/uni-app";
    import {
        setUserAvatar,
        setUserNickName,
        getUserInfo
    } from "@/store/user";
    import {
        getFileExtension,
        isValidUsername
    } from "../../utils/tools.js";
    import {
        getTodayDateString,
        getTodayMonthString
    } from '../../utils/common.js';
    import {
        getUserOpenId
    } from '../../utils/getOpenId.js';
    import md5 from 'js-md5';
    import {
        getTotalUserScore,
        getUserScoreFromCloud,
        saveUserTotalScoreToCloud,
        getUserScore,
        addUserScore,
        saveUserAddScoreToLocal,
        SignInGetScore,
        SignInGetScoreLocal,
        saveUserCloudScoreToLocal
    } from '../../store/scoreManager.js';

    export default {
        data() {
            return {
                user: {},
                openId: ""
            };
        },
        onShow: async function () {
            // 引入公共模块
            this.user = await getUserScoreFromCloud();
        },
        methods: {
            nicknameBlur: function (e) {
                this.user.nickname = e.detail.value;
            },
            handleEditNickname: async function (e) {
                const db = uniCloud.database();
                if (e.detail.value.nickname && e.detail.value.nickname.length > 0) {
                    this.user.nickname = e.detail.value.nickname;
                    const openid = await getUserOpenId();
                    const userInfo = await db.collection("open_user").doc(this.user._id).update({
                        nickName: e.detail.value.nickname,
                        avatar: this.user.avatar
                    });
                } else {
                    uni.showToast({
                        title: "请输入昵称",
                        icon: "none"
                    });
                }
            },
            onChooseAvatar: function (e) {
                uni.showLoading({
                    title: "上传中",
                });

                const { avatarUrl } = e.detail;
                this.user.avatar = avatarUrl;
                const time = new Date().getTime();
                getUserOpenId().then((openid) => {
                    this.openId = openid;
                    const uploadPath = "/resource/guaguale/user/header/" + openId + "-" + time + "." + getFileExtension(
                        avatarUrl);
                    uniCloud.uploadFile({
                        filePath: avatarUrl,
                        cloudPath: uploadPath,
                        cloudPathAsRealPath: true,
                        success: (res) => {
                            this.user.avatar = res.fileID;
                            uni.hideLoading();
                        },
                        fail: (err) => {
                            uni.hideLoading();
                            const uploadURL = "https://mp-b4609b89-f010-4b4d-8ed3-0087451c83a0.cdn.bspapp.com" + uploadPath;
                            this.user.avatar = uploadURL;
                        }
                    });
                });
            },
            submitBtnClick: function () {
                if (!this.user.nickname || this.user.nickname.length < 3) {
                    uni.showToast({
                        title: "用户昵称至少3个字符",
                        icon: "none"
                    });
                    return;
                }
                if (isValidUsername(this.user.nickname) === false) {
                    uni.showToast({
                        title: "用户昵称不合法，不支持符号等特殊字符",
                        icon: "none"
                    });
                    return;
                }

                uni.showLoading({
                    title: "修改中...",
                    mask: true,
                });
                const db = uniCloud.database();
                const updateuserdate = getTodayMonthString();
                db.collection("open_user").doc(this.user._id).update({
                    nickname: this.user.nickname,
                    avatar: this.user.avatar,
                    updateuserdate: updateuserdate
                }).then((e) => {
                    uni.showToast({
                        title: "修改成功！",
                        icon: "none"
                    });
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/index/loading'
                        });
                    }, 1000);
                }).catch((e) => {
                    uni.hideLoading();
                    uni.showToast({
                        title: "修改失败，请稍后再试",
                        icon: "none"
                    });
                });
            }
        }
    };
</script>

<style lang="scss">
	.edit-info {
		width: 100%;
		height: 100%;
		box-sizing: border-box;

		.avatar-wrapper {
			margin-top: 100rpx;
			background-color: #fff;
			border: 0 none;
			line-height: 1.5;

			.avatar {
				width: 180rpx;
				height: 180rpx;
				border-radius: 50%;
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				background-color: #ddd;
			}
		}

		.nickname {
			box-sizing: border-box;
			margin-top: 50rpx;
			height: 100rpx;
			margin-left: 50rpx;
			margin-right: 50rpx;
			position: relative;
			border: 1rpx solid #ccc;
			align-items: center;
			border-radius: 20rpx;
			// padding: 20rpx 20rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: flex-start;

			.input {
				margin-left: 30rpx;
				margin-right: 30rpx;
				width: 100%;
				height: 100%;
			}
		}

		.submit-btn {
			margin-top: 50rpx;
			margin-left: 50rpx;
			margin-right: 50rpx;
			height: 100rpx;
		}
	}
</style>